/*
 * Copyright 2004-2009 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
 * either express or implied. See the License for the specific language
 * governing permissions and limitations under the License.
 */
package susano.common.util;

import java.lang.reflect.Field;
import java.util.logging.Logger;

import susano.common.exception.SusanoRuntimeException;

/**
 * モデルを扱うためのユーティリティ
 *
 * @author tanaka.akira.2006
 * @version $Id$
 *
 */
public final class ModelUtil {

	protected static final Logger logger = Logger.getLogger(ModelUtil.class
			.getName());

	/**
	 * publicフィールドなモデルから {@link BeanMap} を生成します。
	 *
	 * @param <T>
	 * @param model
	 * @return {@link BeanMap}
	 */
	public static <T> BeanMap createBeanMap(final T model) {
		BeanMap bm = new BeanMap();
		modelToBeanMap(model, bm);
		return bm;
	}

	/**
	 * publicフィールドなモデルを {@link BeanMap} へコピーします。
	 *
	 * @param <T>
	 * @param src
	 * @param dst
	 */
	public static <T> void modelToBeanMap(final T src, BeanMap dst) {
		Field[] fs = src.getClass().getFields();
		for (int i = 0; i < fs.length; i++) {
			String key = fs[i].getName();
			Object value = null;
			try {
				value = fs[i].get(src);
			} catch (IllegalArgumentException e) {
				throw new SusanoRuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new SusanoRuntimeException(e);
			}
			dst.put(key, value);
		}
	}

	/**
	 * {@link BeanMap} をpublicフィールドなモデルへコピーします。
	 *
	 * @param <T>
	 * @param src
	 * @param dst
	 */
	public static <T> void beanMapToModel(final BeanMap src, T dst) {
		for (String key : src.keySet()) {
			Field f = null;
			try {
				f = dst.getClass().getField(key);
			} catch (SecurityException e) {
				throw new SusanoRuntimeException(e);
			} catch (NoSuchFieldException e) {
				throw new SusanoRuntimeException(e);
			}
			try {
				f.set(dst, src.get(key));
			} catch (IllegalArgumentException e) {
				throw new SusanoRuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new SusanoRuntimeException(e);
			}
		}
	}
}
